package com.example.dwhne.leonweather.other;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.example.dwhne.leonweather.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Response;

import static com.example.dwhne.leonweather.other.HttpUtil.sendOkHttpRequest;


public class HotCity extends AppCompatActivity {
    private Handler handler;
    private TextView textView;
    private String responseText = null;
    private String url1 = "https://search.heweather" + "" + "" + "" + "" +
            ".com/top?group=cn&key=9a77b5efa51e4f5c9ddacf7f0ddbdd32&number=20";
    private List<String> cityList = new ArrayList<>();
    private Map<String, String> cityMap = new HashMap<>();
    private StringBuilder cities = new StringBuilder();
    private SwipeRefreshLayout swiperereshlayout ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hot_city);

        textView = findViewById(R.id.hotCities_tv);
        swiperereshlayout = findViewById(R.id.swiperereshlayout);
        handler = new FirstHandle();

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(HotCity.this);
        String hotCitiesString = prefs.getString("hotCities", null);

        if (hotCitiesString != null) {
            textView.setText(hotCitiesString);
        } else {

        }

        swiperereshlayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light);
        //给swipeRefreshLayout绑定刷新监听
        swiperereshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //设置2秒的时间来执行以下事件
                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        swiperereshlayout.setRefreshing(false);
                    }
                }, 2000);
            }
        });

    }

    public void click(View view) {
        Thread t = new NetworkThread();
        t.start();
    }

    class FirstHandle extends Handler {
        @Override
        public void handleMessage(Message msg) {
            Log.d("Message", "handleMessage: " + Thread.currentThread().getName());
            int what = msg.what;
            Map<String, String> mCityMap = (Map<String, String>) msg.obj;
            Set<Map.Entry<String, String>> entrySet = mCityMap.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                cities.append(entry.getValue());
            }

            SharedPreferences sp = HotCity.this.getSharedPreferences("SP", MODE_PRIVATE);
            SharedPreferences.Editor editor1  = sp.edit();
            editor1.putString("hotCities", cities.toString());
            editor1.apply();

            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(HotCity.this).edit();
            editor.putString("hotCities", cities.toString());
            editor.apply();

            textView.setText(cities.toString());

//            Log.d(getString(R.string.message), "handleMessage: " + what);
        }
    }

    class NetworkThread extends Thread {

        @Override
        public void run() {

            Log.d("Message", "run: " + getName());

            /*OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
            builder.sslSocketFactory(createSSLSocketFactory());
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });*/
            sendOkHttpRequest(url1, new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.i("IOException", "onResponse: " + e);
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.i("Response", "onResponse: " + response);
                    responseText = response.body().string();
                    Log.i("Response", "onResponse: " + responseText);


                }
            });
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Message msg = handler.obtainMessage();
            HotCitiesBean hotCitiesBean = Utility.handleHotCityResponse(responseText);
            List<HotCitiesBean.HeWeather6Bean> heWeather6BeanList = hotCitiesBean.getHeWeather6();
            HotCitiesBean.HeWeather6Bean basicBeans = heWeather6BeanList.get(0);

            String status = basicBeans.getStatus();
            if (hotCitiesBean != null && status.equals("ok")) {
                List<HotCitiesBean.HeWeather6Bean.BasicBean> basics = basicBeans.getBasic();
                for (HotCitiesBean.HeWeather6Bean.BasicBean basicBean : basics) {
                    cityMap.put(basicBean.getCid(), basicBean.getLocation());
                }
            }
            msg.obj = cityMap;
            handler.sendMessage(msg);
            // Looper 将会调用Handler 的sendMessage(Message msg) 方法在Main Thread 还是Worker Thread 中都可以发送
        }
    }

}
